package com.tarena.lbs.basic.web.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class AdminController {

    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    @Autowired
    private AdminService adminService;

    /**
     * 参考笔记中的 查询admin账号详情的接口文档表格内容
     */
    @GetMapping("/admin/basic/role/detail")
    public Result<AdminVO> detail(@RequestHeader(value = "Authorization",required = false) String jwt) throws BusinessException {
//        @RequestHeader 和 HttpServletRequest.getHeader() 都可以获取请求头中的参数
//        System.out.println(jwt);
//        Integer id = parseJwt2User(jwt);
        //request.getHeader("Authorization");
        //2.调用业务层 查询adminVO
        AdminVO vo = adminService.detail();
        return new Result<>(vo);
    }

    private Integer parseJwt2User(String jwt) throws BusinessException {
        if (jwt != null && jwt.length()>0) {
            log.info("拿到jwt,非空:{},开始解析",jwt);
            UserPrinciple userPrinciple = jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
            return userPrinciple.getId();
        }else {
            log.error("没有jwt,查不到任何数据");
            throw new BusinessException("-2","jwt没值");
        }
    }

    @PostMapping("/admin/basic/role/list")
    public Result<PageResult<AdminVO>> search(@RequestBody AdminQuery adminQuery){
        return new Result<>(adminService.accountPage(adminQuery));
    }

    @PostMapping("/admin/basic/role/add")
    public Result<Void> save(@RequestBody AdminParam adminParam) throws BusinessException {
        adminService.save(adminParam);
        return Result.success();
    }
}
